package com.nhjf.admin.util;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.io.FileUtils;

import com.nhjf.admin.common.util.LogMessage;
import com.nhjf.admin.common.util.SysProperties;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


@SuppressWarnings("restriction")
public class ImageUtil {
	
	public static void main(String args[]){
		try{
			ImageUtil.doCompress("C:/1.jpg", "C:/2.jpg");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 读取图片文件
	 * @param imagePath 图片地址
	 * @return
	 */
	private static BufferedImage readImage(String imagePath) throws Exception{
		// 构造BufferedImage对象  
		BufferedImage srcImage = null;  
		FileInputStream in = null;
        File file = new File(imagePath);  
        in = new FileInputStream(file);  
        byte[] b = new byte[5];  
        in.read(b);  
        srcImage = javax.imageio.ImageIO.read(file); 
        in.close();
        return srcImage;  
	}
	
	
	/**
	 * 将图片文件输出到指定的路径，并设定压缩质量 
	 * @param srcImagePath 原图地址
	 * @param targetImagePath 压缩图片地址
	 * @param quality 压缩质量
	 * @throws Exception
	 */
	public static void doCompress(String srcImagePath,String targetImagePath) throws Exception{
    	 // 判断输出的文件夹路径是否存在，不存在则创建  
        File file = new File(targetImagePath);  
        if (!file.getParentFile().exists()) {  
            file.getParentFile().mkdirs();  
        }
        
        float quality = Float.valueOf(SysProperties.getInstance().get("quality"));
        FileOutputStream targetImage = new FileOutputStream(targetImagePath); 
        BufferedImage srcImage = readImage(srcImagePath);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(targetImage);  
        JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(srcImage);  
        // 压缩质量  
        jep.setQuality(quality, true);  
        encoder.encode(srcImage, jep);  
        targetImage.close();  
    }

	/**
	 * 将图片文件输出到指定的路径，并设定压缩质量（与doCompress方法作用相同，但是使用doCompress方法存在部分图片变色的问题，故增加此方法）
	 * @param srcImagePath
	 * @param targetImagePath
	 * @throws Exception
	 */
	public static void compressPic(String srcImagePath, String targetImagePath) throws Exception {
		// 判断输出的文件夹路径是否存在，不存在则创建 
        File file = new File(targetImagePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Image src = Toolkit.getDefaultToolkit().getImage(srcImagePath);  
        BufferedImage srcImage = ImageUtil.toBufferedImage(src);
        
        float quality = Float.valueOf(SysProperties.getInstance().get("quality"));
        FileOutputStream targetImage = new FileOutputStream(targetImagePath);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(targetImage);
        JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(srcImage);
        jep.setQuality(quality, true);
        encoder.encode(srcImage, jep);
        targetImage.close();
    }
	
	public static BufferedImage toBufferedImage(Image image) {
	    if (image instanceof BufferedImage) {
	        return (BufferedImage) image;
	    }
	    // This code ensures that all the pixels in the image are loaded
	    image = new ImageIcon(image).getImage();
	    BufferedImage bimage = null;
	    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
	    try {
	    	GraphicsDevice gs = ge.getDefaultScreenDevice();
	    	GraphicsConfiguration gc = gs.getDefaultConfiguration();
	        bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), Transparency.OPAQUE);
	    } catch (HeadlessException e) {
	        // The system does not have a screen  
	    }  
	    if (bimage == null) {
	        // Create a buffered image using the default color model
	        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
	    }
	    // Copy image to buffered image
	    Graphics g = bimage.createGraphics();
	    // Paint the image onto the buffered image
	    g.drawImage(image, 0, 0, null);
	    g.dispose();
	    return bimage;
	}
		/**
		 * 删除文件
		 * @param file
		 * @return
		 */
		public boolean deletefile(File file){
			if(file.exists()){
				file.delete();	
				return true;
			}else{
				return false;
			}
		}
		/**
		 * 删除图片
		 * @param filename
		 * @param targetSrc
		 */
		public void deletefiles(String filename,String targetSrc){		
			if(filename!=null&&!"".equals(filename)){
				File target=new File(targetSrc,filename);
				deletefile(target);
			}
		}
		 /**
		  * 对比上传文件类型�Ա��ϴ��ļ�����
		  * @param fileName
		  * @param types
		  * @return
		  */	
		 public String filterDocType(String fileName,String[] types){
	  	   //取得上传文件的文件类型ȡ���ϴ��ļ����ļ�����
	        int position = fileName.lastIndexOf(".");   
	        String extension = "image/"+fileName.substring(position+1);  
	  	  String had = null;
	        //遍历����
	  	   for(String type : types){
	  	    if(type.equals(extension)){
	  	     had ="had";
	  	     break;
	  	    }
	  	   }
	  	   return had;
	  	}
		
		 /**
		  * 重命名文件名
		  * @param fileName
		  * @return
		  */
		 public String generateFileName(String fileName) {   
	         DateFormat format = new SimpleDateFormat("yyMMddHHmmss");   
	         String formatDate = format.format(new Date());   
	            
	         int random = new Random().nextInt(10000);      
	         int position = fileName.lastIndexOf(".");   
	         String extension = fileName.substring(position);   
	            
	         return formatDate + random + extension;   
	     }
		 /**
		  * COPY时重命名文件
		  * @param targetSrc
		  * @param fileName
		  * @return
		  */
		 public String rename(String targetSrc,String fileName){
			 File target=new File(targetSrc,fileName);
			 String rname=generateFileName(fileName);
			 String url=targetSrc+"/"+rname;
			 target.renameTo(new File(url));
			 return rname;
		 }
		 
		 /**
			 * 删除文件夹
			 * @param f
			 * @return
			 */
			public boolean deletedir(File f) {
				if (f.isDirectory()) {
					File[] files = f.listFiles();
					for (int i = 0; i < files.length; i++) {
						if (files[i].isDirectory()){
							deletedir(files[i]);
						}else{
							deletefile(files[i]);
						}
					}
				}
				f.delete();
				return true;
			}
			
			/**
			 * 保存图片
			 * @param filename
			 */
			public void savefile(String srcc, String filename,String targetSrc){	
				try {
					String docSrc =srcc+"/"+filename;
				
					File doc=new File(docSrc);
					if(filename!=null&&!"".equals(filename)){
						File target=new File(targetSrc,filename);
						FileUtils.copyFile(doc, target);
					}
				} catch (IOException e) {
					LogMessage.logwrite(this.getClass(), e.getMessage());
				}
					
			}

			/**
			 * 保存图片2
			 * @param srcc
			 * @param sfile
			 * @param targetSrc
			 * @param tfile
			 */
			public void savefiletwo(String srcc, String sfile,String targetSrc, String tfile){
				try {
					String docSrc =srcc+"/"+sfile;
					File doc=new File(docSrc);		
					File target=new File(targetSrc,tfile);
					FileUtils.copyFile(doc, target);

				} catch (IOException e) {
					LogMessage.logwrite(this.getClass(), e.getMessage());
				}
        }
}